//
//  AnswerWoFixViewController.m
//  dingdang
//
//  Created by hehe on 15/8/10.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "AnswerWoFixViewController.h"
#import "DDShareViewController.h"
#import "DDNetWorkAPIClient.h"

#import "DDMyQuestionDetailCollectionViewCell.h"
#import "DDNetWorkAPIClient.h"
#import "DDMyQuestionDetailCollectionReusableView.h"
#import "DDQuestionAnswerReply.h"
#import "DDQuestionAnswerList.h"
#import "DateUtil.h"
#import "UIImageView+WebCache.h"
#import "CWStarRateView.h"
#import "DDQuestionFollowAnswerViewController.h"

#define tempFix 0

@interface AnswerWoFixViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,DDMyQuestionDetailCollectionViewCellDelegate,CWStarRateViewDelegate,UIAlertViewDelegate>{
    DDNetWorkAPIClient * client;
    NSMutableParagraphStyle *paragraphStyle;
    NSMutableArray * array_showList;
    NSRange timeRange;
    DDSharedUser * shareUser;
    CWStarRateView * starRateView;
    DDQuestionAnswerListCell * hold_followAnswer;
    DDQuestionAnswerListCell * hold_rating;
    DDQuestionAnswerListCell * hold_adopt;
    NSInteger choosedStars;
}

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (weak, nonatomic) IBOutlet UIView *contentOfStarRateView;
@property (weak, nonatomic) IBOutlet UIView *contentOfAlert;
@property (weak, nonatomic) IBOutlet UIView *contentOfAlertInter;
@property(nonatomic,strong)NSDictionary * holdHeadDic;
@property(nonatomic,strong)DDModelMyQuetionsListElement_answerInfo * info_detailInfo;
@property(nonatomic,strong)DDModelMyQuetionsListElement * info_element;
@property(nonatomic,assign) BOOL isReward;
@end

@implementation AnswerWoFixViewController

-(void)viewWillAppear:(BOOL)animated{
    starRateView = [[CWStarRateView alloc]initWithFrame:self.contentOfStarRateView.bounds numberOfStars:5];
    starRateView.delegate = self;
    [self.contentOfStarRateView addSubview:starRateView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self createUI];
    [self createData];
}

-(void)createUI{
    if ([self.pushDB.type isEqualToString:@"2"]) {
        [self addNavigatorTitle:@"被采纳的"];
    }else if ([self.pushDB.type isEqualToString:@"3"]){
        [self addNavigatorTitle:@"回答我的"];
    }else if([self.pushDB.type isEqualToString:@"1"]){
        [self addNavigatorTitle:@"被追问的"];
    }else{
        [self addNavigatorTitle:@"系统消息"];
    }
    
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];

    
    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"top_返回" action:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self AddRightBtnAction:@"分享" normal:@"" selected:@"" action:^{
        [DDShareViewController  showShareWithController:self];
    }];
    
    [self.myCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DDMyQuestionDetailCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([DDMyQuestionDetailCollectionViewCell class])];
    [self.myCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([DDMyQuestionDetailCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([DDMyQuestionDetailCollectionReusableView class])];
    
    client = [[DDNetWorkAPIClient alloc]init];
    [self createData];
    self.contentOfAlertInter.layer.cornerRadius = 10;
    self.contentOfAlertInter.layer.masksToBounds = YES;
}

-(void)createData{
    
    paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 1;
    
    array_showList = [[NSMutableArray alloc]init];
    timeRange.location = 0;
    timeRange.length = 19;
    shareUser = [DDSharedUser shared];
    
    __weak AnswerWoFixViewController *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    
    
    [network mainTopicDetail:@{@"topicId":_pushDB.topicId} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        weakSelf.holdHeadDic = object;
        if (self.holdHeadDic) {
            DDModelMyQuetionsListElement * element = [[DDModelMyQuetionsListElement alloc]initWithDictionary:self.holdHeadDic[@"data"] error:nil];
            if (element) {
                self.info_element = element;
                self.info_detailInfo = [element.info_questions firstObject];
                if (element.info_reward) {
                    self.isReward = YES;
                }else{
                    self.isReward = NO;
                }
            }
        }
        
        [weakSelf.myCollectionView reloadData];
    }];

    
    
//    if ([self.pushDB.type isEqualToString:@"1"]) {
        //被追问
//        [client mainQuestionReplyList:@{@"answerId":self.pushDB.answerId} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//            DDQuestionAnswerReply * replay = (DDQuestionAnswerReply *)object;
//            [array_showList removeAllObjects];
//            [array_showList addObjectsFromArray:replay.list];
//            [weakSelf.myCollectionView reloadData];
//            [weakSelf hideHUD];
//        }];
//    }else if ([self.pushDB.type isEqualToString:@"2"]){
        //被采纳
        
//    }else if ([self.pushDB.type isEqualToString:@"3"]){
        //回答我的
        /*
        excludedUid = "-1";
        pageIndex = 0;
        pageSize = 10;
        qid = 952;
        topicId = 529;
         */
        
        
        [network mainQuestionAnswerList:@{@"topicId":_pushDB.topicId,@"qid":_pushDB.qid,@"excludedUid":@"-1"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            
            DDQuestionAnswerList *mylist = (DDQuestionAnswerList*)object;
            [array_showList removeAllObjects];
            [array_showList addObjectsFromArray:mylist.list];
            [weakSelf.myCollectionView reloadData];
            [weakSelf hideHUD];

            
            
//            DDQuestionAnswerList *mylist = (DDQuestionAnswerList*)object;
//            NSArray *my = mylist.list;
//            NSMutableArray *list = [NSMutableArray arrayWithArray:my];
//            if (my.count > 0) {
//                DDQuestionAnswerListCell *cell = my[0];
//                _questionAnswer = my[0];
//                [network mainQuestionReplyList:@{@"answerId":cell.id} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
//                    
//                    DDQuestionAnswerReply *reply = (DDQuestionAnswerReply *)object;
//                    [list addObjectsFromArray:reply.list];
//                    
//                    NSMutableArray *secondArray = [NSMutableArray array];
//                    [secondArray addObject:list];
//                    [array_showList addObject:secondArray];
//                    [weakSelf.tableView reloadData];
//                }];
//            }
        }];
//    }else{
    
//    }
}

-(void)regetData{
    __weak AnswerWoFixViewController *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network mainQuestionAnswerList:@{@"topicId":_pushDB.topicId,@"qid":_pushDB.qid,@"excludedUid":@"-1"} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        DDQuestionAnswerList *mylist = (DDQuestionAnswerList*)object;
        [array_showList removeAllObjects];
        [array_showList addObjectsFromArray:mylist.list];
        [weakSelf.myCollectionView reloadData];
        [weakSelf hideHUD];
    }];

}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        DDMyQuestionDetailCollectionReusableView * tempView =  [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([DDMyQuestionDetailCollectionReusableView class]) forIndexPath:indexPath];
        tempView.info_detail = self.info_detailInfo;
        tempView.info_element = self.info_element;
        [tempView fixView];
       
        
        return tempView;
    }else{
        return nil;
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return array_showList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DDMyQuestionDetailCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DDMyQuestionDetailCollectionViewCell class]) forIndexPath:indexPath];
    
    float tempHeight = 60.0;
    
    DDQuestionAnswerListCell * element = array_showList[indexPath.row];
    cell.label_userName.text = element.userName;
    [cell.imageView_head sd_setImageWithURL:[NSURL URLWithString:element.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]];
    cell.label_time.text = element.answerTime;
    
    
    
    for (DDQuestionAnswerExplanation * explan in element.explanation) {
        if ([explan.type isEqualToString:@"TEXT"]) {
            cell.label_body.text = explan.text;
            tempHeight += 30;
        }else if ([explan.type isEqualToString:@"IMAGE"]){
            [cell.imageView_body sd_setImageWithURL:[NSURL URLWithString:explan.url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]];
            tempHeight += 140;
        }
    }
    
    cell.contentOfBottom.frame = CGRectMake(0, tempHeight, CGRectGetWidth([[UIScreen mainScreen] bounds]), 30);
    cell.btn_openOrCloseFollowAnswer.frame = CGRectMake(CGRectGetWidth([[UIScreen mainScreen]bounds]) - 40, tempHeight - 30, 30, 30);
    
    
    //    if (element.adopted.boolValue == YES) {
    //        cell.backgroundColor = [UIColor redColor];
    //    }else{
    //        cell.backgroundColor = [UIColor whiteColor];
    //    }
    
    cell.btn_bottom_followAsk.hidden =
    cell.btn_bottom_adopt.hidden =
    cell.btn_bottom_rating.hidden = NO;
    if (self.isReward == YES) {
        if (element.adopted) {
            cell.info_adopt = element.adopted;
            cell.btn_bottom_adopt.hidden = YES;
        }else{
            cell.info_adopt = nil;
            cell.btn_bottom_adopt.hidden = NO;
        }
    }else{
        cell.btn_bottom_adopt.hidden = YES;
    }
    
    if (element.score) {
        cell.info_starRating = element.score.integerValue;
        //            [cell.contentOfBottom bringSubviewToFront:cell.contentOfBottom_followAnswer];
        cell.btn_bottom_rating.hidden = YES;
    }else{
        cell.info_starRating = 0;
        //            [cell.contentOfBottom bringSubviewToFront:cell.contentOfBottom_ratingAndAnswer];
        cell.btn_bottom_rating.hidden = NO;
    }
    
    
    
    
    //    if (element.score) {
    //        cell.info_starRating = element.score.integerValue;
    //        [cell.contentOfBottom bringSubviewToFront:cell.contentOfBottom_followAnswer];
    //    }else{
    //        cell.info_starRating = 0;
    //        [cell.contentOfBottom bringSubviewToFront:cell.contentOfBottom_ratingAndAnswer];
    //    }
    
    if (shareUser.userInfo.uid.integerValue == element.uid.integerValue) {
        cell.contentOfBottom.hidden = YES;
        
    }else{
        cell.contentOfBottom.hidden = NO;
    }
    
    if (element.info_isShowList.boolValue == YES) {
        [cell.btn_openOrCloseFollowAnswer setImage:[UIImage imageNamed:@"上三角"] forState:UIControlStateNormal];
    }else{
        [cell.btn_openOrCloseFollowAnswer setImage:[UIImage imageNamed:@"下三角"] forState:UIControlStateNormal];
    }
    
    cell.isOpenFollowAsk = element.info_isShowList.boolValue;
    cell.info_followAskList = element.info_exFollowAsk;
    cell.delegate = self;
    [cell fixCell];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize tempSize;
    CGFloat addHeight = 0.0;
    DDQuestionAnswerListCell * element = array_showList[indexPath.row];
    for (DDQuestionAnswerExplanation * explan in element.explanation) {
        if ([explan.type isEqualToString:@"TEXT"]) {
            addHeight += 30;
        }else if ([explan.type isEqualToString:@"IMAGE"]){
            addHeight += 140;
        }
    }
    
    if (shareUser.userInfo.uid.integerValue != element.uid.integerValue) {
        addHeight += 30;
    }
    
    tempSize.width = self.view.frame.size.width;
    tempSize.height = 60 + addHeight;
    
    if (element.info_isShowList.boolValue == YES) {
        float totalHeight = 50.0;
        for (int i = 0; i < element.info_exFollowAsk.list.count; i++) {
            DDQuestionAnswerReplyCell * tempModel = element.info_exFollowAsk.list[i];
            totalHeight += 50;
            for (DDQuestionAnswerReplyContent * content in tempModel.content) {
                if ([content.type isEqualToString:@"TEXT"]) {
                    CGRect tempRect = [content.text boundingRectWithSize:CGSizeMake(CGRectGetWidth([[UIScreen mainScreen] bounds]) - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14],NSParagraphStyleAttributeName : paragraphStyle} context:nil];
                    totalHeight += 20;
                    totalHeight += tempRect.size.height;
                }else if ([content.type isEqualToString:@"IMAGE"]){
                    totalHeight += 210;
                }else if ([content.type isEqualToString:@"VOICE"]){
                    totalHeight += 30;
                }
                
                
            }
        }
        tempSize.height = tempSize.height + totalHeight;
    }
    
    
    return tempSize;
}

-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    BOOL isHaveImage = NO;
    float addHeight = 0;

    for (DDModelMyQuetionsListElement_answerInfo_body * tempBody in self.info_detailInfo.info_body) {
        if ([tempBody.info_type isEqualToString:@"IMAGE"]){
            isHaveImage = YES;
        }else if([tempBody.info_type isEqualToString:@"TEXT"]){
            CGRect tempRect = [tempBody.info_text boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15],NSParagraphStyleAttributeName : paragraphStyle} context:nil];
            
            addHeight += (tempRect.size.height - 21);
            addHeight += 5;
        }
    }
    
    if (isHaveImage == YES) {
        addHeight = 100;
    }
    
    if (self.info_detailInfo.info_typeName) {
        addHeight += 30;
    }
    
    NSInteger optionsCount = self.info_detailInfo.info_options.count;
    CGFloat heightOfContentOptions = 55 * optionsCount;
    addHeight += heightOfContentOptions;

    CGSize size = {self.view.frame.size.width, 120 + addHeight};
    return size;
}

- (IBAction)btnClick_alert_cancel:(id)sender {
    self.contentOfAlert.hidden = YES;
    choosedStars = 0;
}
- (IBAction)btnClick_alert_confirm:(id)sender {
    self.contentOfAlert.hidden = YES;
    if (choosedStars == 0) {
        
    }else{
        [self showHUD:@""];
        NSDictionary * paramDic = @{@"answerId" : hold_rating.id,
                                    @"score" : [NSNumber numberWithInteger:choosedStars]};
        [client mainQuestionAnswerEvaluate:paramDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            [array_showList removeAllObjects];
            [self hideHUD];
            [self regetData];
        }];
    }
    
}


#pragma mark - DDMyQuestionDetailCollectionViewCellDelegate
-(void)starRateWithCell:(DDMyQuestionDetailCollectionViewCell *)tempCell{
    NSIndexPath * indexPath = [self.myCollectionView indexPathForCell:tempCell];
    self.contentOfAlert.hidden = NO;
    choosedStars = 0;
    hold_rating = array_showList[indexPath.row];
}
-(void)followAnswerWithCell:(DDMyQuestionDetailCollectionViewCell *)tempCell{
    NSIndexPath * indexPath = [self.myCollectionView indexPathForCell:tempCell];
    hold_followAnswer = array_showList[indexPath.row];
    DDQuestionFollowAnswerViewController * vc = [[DDQuestionFollowAnswerViewController alloc]init];
    vc.info_element = hold_followAnswer;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)adoptWithCell:(DDMyQuestionDetailCollectionViewCell *)tempCell{
    NSIndexPath * indexPath = [self.myCollectionView indexPathForCell:tempCell];
    hold_adopt = array_showList[indexPath.row];
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"采纳答案" message:@"" delegate:self cancelButtonTitle:@"拒绝" otherButtonTitles:@"采纳", nil];
    [alert show];
}

-(void)openOrCloseFollowAsk:(DDMyQuestionDetailCollectionViewCell *)tempCell{
    NSIndexPath * indexPath = [self.myCollectionView indexPathForCell:tempCell];
    
    __block DDQuestionAnswerListCell * element = array_showList[indexPath.row];
    element.info_isShowList = [NSNumber numberWithBool:!element.info_isShowList.boolValue ];
    if (element.info_isShowList.boolValue == YES) {
        [self showHUD:@""];
        NSDictionary * tempDic = @{@"answerId" : element.id ,
                                   @"pageIndex" : [NSNumber numberWithInteger:0],
                                   @"pageSize" : [NSNumber numberWithInteger:100]};
        __weak AnswerWoFixViewController * weakSelf = self;
        [client mainQuestionReplyList:tempDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            DDQuestionAnswerReply * model = object;
            element.info_exFollowAsk = model;
            //            [weakSelf.myCollectionView reloadData];
            [weakSelf.myCollectionView reloadItemsAtIndexPaths:@[indexPath]];
            [weakSelf hideHUD];
        }];
    }else{
        [self.myCollectionView reloadItemsAtIndexPaths:@[indexPath]];
        [self.myCollectionView reloadData];
    }
    
}

- (void)starRateView:(CWStarRateView *)starRateView scroePercentDidChange:(CGFloat)newScorePercent{
    choosedStars = newScorePercent * 5;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"采纳答案"]) {
        NSDictionary * tempDic = nil;
        if (buttonIndex == 1) {
            tempDic =  @{
                         @"answerId" : hold_adopt.id,
                         @"result" : [NSNumber numberWithBool:YES],
                         };
        }else{
            tempDic =  @{
                         @"answerId" : hold_adopt.id,
                         @"result" : [NSNumber numberWithBool:NO],
                         };
        }
        [self showHUD:@""];
        __weak AnswerWoFixViewController * weakSelf = self;
        [client mainQuestionAnswerAdopt:tempDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            [weakSelf regetData];
            [weakSelf hideHUD];
        }];
        
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
